package com.unknownman.block.transaction;

import com.unknownman.block.dto.ChainContractComposition;
import com.unknownman.block.service.TChainConfigService;
import com.unknownman.block.transaction.subscribe.BaseTranFilter;
import com.unknownman.block.transaction.subscribe.EthTranFilter4;
import java.util.Collections;
import lombok.extern.slf4j.Slf4j;
import org.cloud.utils.CollectionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 初始化链订阅
 */
@Slf4j
@Component
public class InitChainTranSubscribe {

    @Autowired
    private TChainConfigService chainConfigService;

    private Map<String, BaseTranFilter> chainTranFilter = new HashMap<>();

    public void initSubscribe() {
        List<ChainContractComposition> chainContractCompositionList = chainConfigService.getChainContractCompositionList(true);
        if (CollectionUtil.single().isEmpty(chainContractCompositionList)) {
            return;
        }
        for (ChainContractComposition chainContractComposition : chainContractCompositionList) {
            BaseTranFilter tranFilter = chainTranFilter.get(chainContractComposition.getChainSymbol());
            if (tranFilter != null && !tranFilter.isDisposed()) {
                continue;
            }
            createChainSubscribe(chainContractComposition);
        }
    }

    public void clearSubscribe(Long chiaConfigId) {
        ChainContractComposition composition = chainConfigService.getChainContractCompositionById(chiaConfigId);
        BaseTranFilter tranFilter = chainTranFilter.get(composition.getChainSymbol());
        if (tranFilter != null) {
            tranFilter.stopSubscribe();
            chainTranFilter.remove(composition.getChainSymbol());
        }
    }

    private void createChainSubscribe(ChainContractComposition chainContractComposition) {
        BaseTranFilter tranFilter = getTranFilter(chainContractComposition);
        boolean b = tranFilter.addFilter(BigInteger.valueOf(chainContractComposition.getBlockNumber()));
        if (b) {
            chainTranFilter.put(chainContractComposition.getChainSymbol(), tranFilter);
        }
    }


    @Value("#{'${system.scan.rpc.list:}'.empty ? null : '${system.scan.rpc.list:}'.split(',')}")
    private List<String> rpcList;   //判断空 null

    private BaseTranFilter getTranFilter(ChainContractComposition chainContractComposition) {

        if (rpcList == null || rpcList.size() == 0) {
            return new EthTranFilter4(chainContractComposition, Collections.singletonList(chainContractComposition.getRpcAddress()));
        } else {
            return new EthTranFilter4(chainContractComposition, rpcList);
        }


    }
}
